import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/product_workreportrecord_odoo_api.dart';
import 'package:flutter_admin/models/odoo/udt_tb_workreportrecord.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/pages/common/date_time_select.dart';
import 'package:flutter_admin/pages/odoo/product_workreportrecord/product_workreport_list.dart';
import 'package:flutter_admin/pages/odoo/product_workreportrecord/product_workreportrecord_dialog.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

class ProductWorkreportrecordList extends StatefulWidget {
  ProductWorkreportrecordList({Key? key}) : super(key: key);

  @override
  _ProductWorkreportrecordListState createState() =>
      _ProductWorkreportrecordListState();
}

class _ProductWorkreportrecordListState
    extends State<ProductWorkreportrecordList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  UdtTbWorkreportrecord udtTbWorkreportrecord = UdtTbWorkreportrecord();
  DateFormat format = DateFormat('yyyy-MM-dd HH:mm:ss');

  List<SelectOptionVO> workshopList = [];
  List<SelectOptionVO> teamList = [];
  List<UdtTbWorkreportrecord> selectedList = [];
  UserInfo userInfo = StoreUtil.getCurrentUserInfo();

  @override
  void initState() {
    super.initState();
    udtTbWorkreportrecord.startDate = Utils.getDate()+" 00:00:00";
    udtTbWorkreportrecord.endDate = Utils.getDate()+" 23:59:59";
    udtTbWorkreportrecord.workshopId = userInfo.deptId;
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    if (userInfo.major != null) {
      workshopList = await DynamicDataApi.getModelSelect(
          model: "hr.department",
          name: "complete_name",
          key: "parent_id",
          operator: "!=",
          val: null);
    }
    teamList = await DynamicDataApi.getModelSelect(
        model: "base.team",
        name: "teamname",
        key: 'workshop_id',
        val: int.parse(userInfo.deptId!));
    _query();
  }

  @override
  Widget build(BuildContext context) {
    UserInfo userInfo = StoreUtil.getCurrentUserInfo();

    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          DateTimeSelect(
            context,
            width: 230,
            label: '报工开始日期',
            value: udtTbWorkreportrecord.startDate,
            lastDate: isNotBlank(udtTbWorkreportrecord.endDate)
                ? format.parse(udtTbWorkreportrecord.endDate!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              udtTbWorkreportrecord.startDate = v;
              setState(() {});
            },
            onSaved: (v) {
              udtTbWorkreportrecord.startDate = v;
            },
          ),
          DateTimeSelect(
            context,
            width: 230,
            label: '报工结束日期',
            value: udtTbWorkreportrecord.endDate,
            firstDate: isNotBlank(udtTbWorkreportrecord.startDate)
                ? format.parse(udtTbWorkreportrecord.startDate!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              udtTbWorkreportrecord.endDate = v;
              setState(() {});
            },
            onSaved: (v) {
              udtTbWorkreportrecord.endDate = v;
            },
          ),
          userInfo.major != null
              ? CrySelect(
                  width: 280,
                  label: '生产车间',
                  dataList: workshopList,
                  value: udtTbWorkreportrecord.workshopId,
                  onSaved: (v) {
                    udtTbWorkreportrecord.workshopId = v;
                  },
                  onChange: (v) async {
                    if (udtTbWorkreportrecord.workshopId != v) {
                      formKey.currentState!.save();
                      udtTbWorkreportrecord.workshopId = v;
                      udtTbWorkreportrecord.teamId = null;
                      try {
                        teamList = await DynamicDataApi.getModelSelect(
                            model: "base.team",
                            name: "teamname",
                            key: 'workshop_id',
                            val: int.parse(v));
                      } catch (e) {
                        teamList = [];
                      }
                      setState(() {});
                    }
                  },
                )
              : CryInput(
                  width: 200,
                  label: '生产车间',
                  enable: false,
                  value: userInfo.deptName,
                ),
          CrySelect(
            width: 280,
            label: '班组',
            dataList: teamList,
            value: udtTbWorkreportrecord.teamId,
            onSaved: (v) {
              udtTbWorkreportrecord.teamId = v;
            },
          ),
          CryInput(
            width: 160,
            label: '报工人',
            value: udtTbWorkreportrecord.reportworkerName,
            onSaved: (v) {
              udtTbWorkreportrecord.reportworkerName = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('报工人')),
        DataColumn(label: Text('报工日期')),
        DataColumn(label: Text('开机时间')),
        DataColumn(label: Text('关机时间')),
        DataColumn(label: Text('报工数量')),
        DataColumn(label: Text('换模个数')),
        DataColumn(label: Text('刀数')),
        DataColumn(label: Text('板材消耗张数')),
        DataColumn(label: Text('班组')),
        DataColumn(label: Text('生产车间')),
        DataColumn(label: Text('备注')),
      ],
      getCells: (m) {
        UdtTbWorkreportrecord udtTbWorkreportrecord =
            UdtTbWorkreportrecord.fromReportMap(m);
        return [
          DataCell(Text(udtTbWorkreportrecord.reportworkerName ?? '--')),
          DataCell(Text(udtTbWorkreportrecord.reportDate ?? '--')),
          DataCell(Text(udtTbWorkreportrecord.startDate ?? '--')),
          DataCell(Text(udtTbWorkreportrecord.endDate ?? '--')),
          DataCell(Text(udtTbWorkreportrecord.qualifiedquantity != null
              ? udtTbWorkreportrecord.qualifiedquantity.toString()
              : '--')),
          DataCell(Text(udtTbWorkreportrecord.replacenumber != null
              ? udtTbWorkreportrecord.replacenumber.toString()
              : '--')),
          DataCell(Text(udtTbWorkreportrecord.cutting != null
              ? udtTbWorkreportrecord.cutting.toString()
              : '--')),
          DataCell(Text(udtTbWorkreportrecord.unqualifiedquantity != null
              ? udtTbWorkreportrecord.unqualifiedquantity.toString()
              : '--')),
          DataCell(Text(udtTbWorkreportrecord.teamName ?? '--')),
          DataCell(Text(udtTbWorkreportrecord.workshopName ?? '--')),
          DataCell(Text(m['all_remark'] ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButton(
          label: "报工人明细",
          iconData: Icons.view_headline,
          onPressed: selectedList.length == 1
              ? () => _openDetail(selectedList[0])
              : null,
        ),
        CryButton(
          label: "导出",
          onPressed: () => _generateExcel(),
          iconData: Icons.import_export_outlined,
        )
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  Future<dynamic> findAll() async {
    formKey.currentState?.save();
    List<UdtTbWorkreportrecord> resultList = [];
    ResponseBodyApi responseBodyApi =
        await ProductWorkreportrecordOdooApi.findAll(data: {
      "domainList": udtTbWorkreportrecord.toReportDomainList(),
    });
    if (responseBodyApi.success!) {
      resultList = responseBodyApi.data
              .map<UdtTbWorkreportrecord>(
                  (e) => UdtTbWorkreportrecord.fromReportMap(e))
              .toList() ??
          [];
    }
    return resultList;
  }

  _generateExcel() async {
    List<UdtTbWorkreportrecord> selectedList = await findAll();
    if (selectedList == null) {
      return;
    }
    List<Map> map = [
      {
        'name': 'reportworkerName',
        'label': '报工人',
        'columnWidth': 10.0,
      },
      {
        'name': 'reportDate',
        'label': '报工日期',
        'columnWidth': 16.0,
      },
      {
        'name': 'startDate',
        'label': '开机时间',
        'columnWidth': 16.0,
      },
      {
        'name': 'endDate',
        'label': '关机时间',
        'columnWidth': 16.0,
      },
      {
        'name': 'qualifiedquantity',
        'label': '报工数量',
        'columnWidth': 12.0,
      },
      {
        'name': 'replacenumber',
        'label': '换模个数',
        'columnWidth': 12.0,
      },
      {
        'name': 'cutting',
        'label': '刀数',
        'columnWidth': 12.0,
      },
      {
        'name': 'unqualifiedquantity',
        'label': '板材消耗张数',
        'columnWidth': 18.0,
      },
      {
        'name': 'teamName',
        'label': '班组',
        'columnWidth': 18.0,
      },
      {
        'name': 'workshopName',
        'label': '生产车间',
        'columnWidth': 18.0,
      },
    ];
    Utils.generateExcel(
        fileName: "车间人员报工数据统计", configure: map, data: selectedList);
  }

  _openDetail(UdtTbWorkreportrecord udtTbWorkreportrecord) {
    Utils.fullscreenDialog(
        ProductWorkreportList(udtTbWorkreportrecord: udtTbWorkreportrecord));
  }

  _reset() async {
    UserInfo userInfo = StoreUtil.getCurrentUserInfo();

    udtTbWorkreportrecord = UdtTbWorkreportrecord();
    formKey.currentState!.reset();
    udtTbWorkreportrecord.startDate = Utils.getDate()+" 00:00:00";
    udtTbWorkreportrecord.endDate = Utils.getDate()+" 23:59:59";
    udtTbWorkreportrecord.workshopId = userInfo.deptId;
    teamList = await DynamicDataApi.getModelSelect(
        model: "base.team",
        name: "teamname",
        key: 'workshop_id',
        val: int.parse(udtTbWorkreportrecord.workshopId!));
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await ProductWorkreportrecordOdooApi.page(
        data: {
          "page": page,
          "domainList": udtTbWorkreportrecord.toReportDomainList()
        });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductWorkreportrecordDialog(),
      ),
    ).then((v) {
      if (v != null) {
        udtTbWorkreportrecord = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<UdtTbWorkreportrecord>(
                (e) => UdtTbWorkreportrecord.fromReportMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.dmsFile) {
          _openDetail(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.view_agenda_rounded),
            enabled: selectedList.length == 1,
            title: Text('产品明细'),
          ),
        ),
      ],
    );
  }
}
